﻿using LD.Model;
using LD.Quartz;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using ScottPlot.Plottable;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LD
{
    public partial class FrmChart : FrmBase
    {
        private const string mFormat = "yyyy-MM-dd HH:mm:ss";
        private string saveDay;
        private string whiteTime;
        private string blackTime;

        public FrmChart()
        {
            InitializeComponent();
            this.Shown += FrmChart_Shown;
        }

        private void FrmChart_Shown(object sender, EventArgs e)
        {
            CreateUI();
            Init();
        }

        private void CreateUI()
        {
            this.formsPlot1.Configuration.ScrollWheelZoom = false;
            this.formsPlot1.Configuration.LockHorizontalAxis = false;
            this.formsPlot1.Configuration.LockVerticalAxis = false;

            //double[] values1 = { 26, 20, 23, 7, 16 };
            //double[] values2 = { 15, 4, 9, 7, 7 };
            //double[] positions = { 0, 1, 2, 3, 4 };
            //string[] labels = { "PHP", "JS", "C++", "GO", "VB" };
            //mPlot.AddBar(values1);
            //mPlot.AddBar(values2);
            //mPlot.XTicks(labels);
            //mPlot.SetAxisLimits(yMin: 0);
            //formsPlot1.Refresh();

            //var plt = formsPlot2.Plot;
            //double[] _values = { 50, 3 };
            //var ple = plt.AddPie(_values);
            //ple.ShowValues = true;
            //formsPlot2.Refresh();


        }

        private void Init()
        {
            #region 加载参数
            Dictionary<string, string> data = Cache.GetCache("ChartParam") != null ? JsonConvert.DeserializeObject<Dictionary<string, string>>(Cache.GetCache("ChartParam")?.ToString()) : null;
            if (data != null)
            {
                saveDay = txt_saveDay.Text = data["SaveDay"];
                whiteTime = dtp_white.Text = data["WhiteTime"];
                blackTime = dtp_black.Text = data["BlackTime"];
            }
            #endregion

            Chart1();
            Chart2();
        }

        private void Chart1()
        {
            DateTime beginTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + whiteTime);
            if (beginTime > DateTime.Now) // 未到第二天白班时间
                beginTime = beginTime.AddDays(-1);
            List<Plot1Model> data = new List<Plot1Model>();
            //填补0数据
            for (int i = beginTime.Hour; i < 24; i++)
            {
                data.Add(new Plot1Model() { Time = i + "" });
            }
            for (int i = 0; i < beginTime.Hour; i++)
            {
                data.Add(new Plot1Model() { Time = i + "" });
            }

            var tmpData = DBHelper.Instance.Sql.Queryable<TB_Product>().Where(x => x.StartTime >= beginTime)
                     //.GroupBy(y => new { y.Result, Time = y.StartTime.ToString("%H") })
                     //.Select(y => new Plot1Model
                     //{
                     //    Time = y.StartTime.ToString("%H"),
                     //    Result = y.Result,
                     //    Num = SqlFunc.AggregateCount(y.Result)
                     //})
                     .ToList();

            foreach (var item in data)
            {
                var ok = 0;// tmpData.Where(p => p.StartTime.ToString("%H") == item.Time && p.Result == WipType.OK).Count();
                var ng = 0;// tmpData.Where(p => p.StartTime.ToString("%H") == item.Time && p.Result == WipType.NG).Count();
                item.OK = ok;
                item.NG = ng;
            }

            var mPlot = formsPlot1.Plot;
            mPlot.Clear();

            if (data.Count > 0)
            {
                var _x = data.Select(p => (double)p.NG + p.OK).ToArray(); //data.Where(x => x.Result == WipType.NG).Select(y => (double)y.Num).ToArray();
                var _y = data.Select(p => (double)p.NG).ToArray(); //data.Where(x => x.Result == WipType.NG).Select(y => (double)y.Num).ToArray();
                mPlot.AddBar(_x);
                mPlot.AddBar(_y);
                mPlot.XTicks(data.Select(y => y.Time).ToArray());
            }
            else
            {

                var _values = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                var _labels = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
                mPlot.AddBar(_values);
                mPlot.XTicks(_labels);
            }
            mPlot.SetAxisLimits(yMin: 0);
            formsPlot1.Refresh();
        }
        private void Chart2()
        {
            DateTime beginTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + whiteTime);
            if (beginTime > DateTime.Now) // 未到第二天白班时间
                beginTime = beginTime.AddDays(-1);

            double[] _values = DBHelper.Instance.Sql.Queryable<TB_Product>().Where(x => x.StartTime > beginTime)
                       .GroupBy(y => new { y.Result })
                       .Select(y => SqlFunc.ToDouble(SqlFunc.AggregateCount(y.Result)))
                       .ToArray();

            var plt = formsPlot2.Plot;
            plt.Clear();
            PiePlot pie;
            if (_values.Length > 0)
                pie = plt.AddPie(_values);
            else
                pie = plt.AddPie(new double[] { 0, 0 });

            pie.SliceLabels = new string[] { "OK", "NG" };
            pie.ShowValues = true;
            pie.ShowLabels = true;

            //pie.SliceLabelPosition = 0.7;
            //pie.SliceLabelColors = pie.SliceFillColors;
            plt.Legend();
            formsPlot2.Refresh();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var data = new
            {
                SaveDay = txt_saveDay.Text,
                WhiteTime = dtp_white.Text,
                BlackTime = dtp_black.Text,
            };

            Cache.SetCache("ChartParam", JsonConvert.SerializeObject(data));
            Cache.SaveCache();

            saveDay = data.SaveDay;
            whiteTime = data.WhiteTime;
            blackTime = data.BlackTime;

            MessageBox.Show("保存成功");
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            DateTime begin = Convert.ToDateTime(dtp_search_begin.Text + " 00:00:00");
            DateTime end = Convert.ToDateTime(dtp_search_end.Text + " 23:59:59");
            string result = cb_res2.Text;
            string barCode = tb_Barcode2.Text;

            var data = DBHelper.Instance.Sql.Queryable<TB_Product>().Where(x => x.StartTime > begin && x.StartTime <= end && x.Result.Contains(result)&& x.Result.Contains(result))
                  .GroupBy(y => new { Time = y.StartTime.ToString("yyyy-MM-dd") })
                  .Select(y => new
                  {
                      日期 = y.StartTime.ToString("yyyy-MM-dd"),
                      OK数量 = 0,// SqlFunc.Subqueryable<TB_Product>().Where(a => a.StartTime.ToString("yyyy-MM-dd") == y.StartTime.ToString("yyyy-MM-dd") && a.Result == WipType.OK).Count(),
                      NG数量 = 0,// SqlFunc.Subqueryable<TB_Product>().Where(a => a.StartTime.ToString("yyyy-MM-dd") == y.StartTime.ToString("yyyy-MM-dd") && a.Result == WipType.NG).Count(),
                  }).ToList();

            this.dgv_channeng.DataSource = data;
        }

        private void btn_export_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            if (this.dgv_channeng.Rows.Count == 0)
            {
                MessageBox.Show("无数据");
                return;
            }

            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                filePath = fileDialog.FileName;
                if (string.IsNullOrEmpty(Path.GetExtension(filePath)))
                    filePath += ".csv";

                StreamWriter sw = new StreamWriter(filePath, true, Encoding.UTF8);
                string str = $"条码,开始时间,结束时间,CT,结果,备注\t\n";
                sw.Write(str);

                for (int i = 0; i < this.dgv_channeng.RowCount; i++)
                {
                    str = this.dgv_channeng[0, i].Value + "," + 
                            this.dgv_channeng[1, i].Value + "," +
                            this.dgv_channeng[2, i].Value + "," +
                            this.dgv_channeng[3, i].Value + ","+
                            this.dgv_channeng[4, i].Value + ","+
                            this.dgv_channeng[5, i].Value + "\t\n";
                    sw.Write(str);
                }
                sw.Close();
            }
        }

        private void btn_search2_Click(object sender, EventArgs e)
        {
            DateTime begin = Convert.ToDateTime(dtp_search_begin2.Text + ":00");
            DateTime end = Convert.ToDateTime(dtp_search_end2.Text + ":59");
            string result = cb_res2.Text;
            string barCode = tb_Barcode2.Text;
            var data = DBHelper.Instance.Sql.Queryable<TB_Product>().Where(x => x.StartTime > begin && x.StartTime <= end && x.Result.Contains(result) && x.Barcode.Contains(barCode))
                  .Select(y => new
                  {
                      条码 = y.Barcode,
                      开始时间 = y.StartTime.ToString(mFormat),
                      结束时间 = y.EndTime == null ? "" : y.EndTime.Value.ToString(mFormat),
                      y.CT,
                      结果 = y.Result,
                      备注 = y.Remark,
                      y.Pid,
                  }).ToList();

            this.dgv_product.DataSource = data;
            //隐藏最后一列
            this.dgv_product.Columns[this.dgv_product.ColumnCount - 1].Visible = false;
        }

        private void btn_export2_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            if (this.dgv_product.Rows.Count == 0)
            {
                MessageBox.Show("无数据");
                return;
            }

            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                filePath = fileDialog.FileName;
                if (string.IsNullOrEmpty(Path.GetExtension(filePath)))
                    filePath += ".csv";

                StreamWriter sw = new StreamWriter(filePath, true, Encoding.UTF8);
                string str = "条码" + "," + "时间" + "," + "数据" + "," + "结果" + "\t\n";
                sw.Write(str);

                for (int i = 0; i < this.dgv_product.RowCount; i++)
                {
                    str = this.dgv_product[0, i].Value + "," + this.dgv_product[1, i].Value + "," + this.dgv_product[2, i].Value + "," + this.dgv_product[3, i].Value + "\t\n";
                    sw.Write(str);
                }
                sw.Close();
            }
        }

        private void FrmChart_VisibleChanged(object sender, EventArgs e)
        {
            timer2.Enabled = this.Visible;
            //if (((FrmChart)sender).Visible)
            //{
            //    timer1 = new Timer();
            //    timer1.Interval = 5000;
            //    timer1.Enabled = true;
            //    timer1.Tick += new EventHandler(TimerAction);//添加事件
            //}
            //else
            //{
            //    timer1.Stop();
            //}
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            Chart1();
            Chart2();
        }

        private void FrmChart_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timer2.Enabled = false;
        }
        private void UpdatePlan()
        {
            if (int.TryParse(this.txt_saveDay.Text, out var timer) && timer > 0)
            {
                //修改任务计划时间
                string cron = $"0 0/{timer} * * * ? *";
                QuartzUtil.UpdateTime("DeleteDBJob", cron);

                //add
                QuartzUtil.AddJob<DeleteDBJob>("DeleteDBJob", cron);
            }
        }

        private void dgv_product_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                string pid = this.dgv_product.Rows[e.RowIndex].Cells["Pid"].Value as string;
                FrmScrewDataDetail screwDetail = new FrmScrewDataDetail(pid);
                screwDetail.ShowDialog();
            }
        }
    }
}
